
#include "PreHeader.h"
#include "cStageManager.h"

#include "cLogicDataManager.h"
#include "cLogicManager.h"

cStageManager::cStageManager()
{
	m_start = false;

	m_stageID = -1;
	m_timeLineIndex = 0;
	m_stageData = NULL;
}

cStageManager::~cStageManager()
{
}

void cStageManager::Init(const sStageManagerDesc& desc)
{
	m_parent = desc.parent;
	m_logicManager = desc.logicManager;
}

void cStageManager::Start(tInt stageID)
{
	m_stageID = stageID;
	m_timeLineIndex = 0;
	m_stageData = cLogicDataManager::it()->GetStageData(m_stageID);

	const nStageFormat01::sStage::sTimeLine::sProperty& property = m_stageData->timeLine.propertyArray[0];
	m_stageTimer.Init(property.time);

	m_start = true;
	m_stageDelayTimer.Clear();
}

void cStageManager::Stop()
{
	m_start = false;
	m_stageDelayTimer.Clear();
}

void cStageManager::Update(float dt)
{
	if (m_stageDelayTimer.IsUsing() == true)
	{
		m_stageDelayTimer.Update(dt);
		if (m_stageDelayTimer.IsDone() == true)
		{
			m_logicManager->StageClear();
			m_stageDelayTimer.Clear();
		}
	}

	if (m_start == true)
	{
		m_stageTimer.Update(dt);
		if (m_stageTimer.IsDone() == true)
		{
			const nStageFormat01::sStage::sTimeLine::sProperty& property = m_stageData->timeLine.propertyArray[m_timeLineIndex];
			const nFoodFormat01::sFood* foodData = cLogicDataManager::it()->GetFoodData(property.foodID);

			if (foodData == NULL)
			{
				m_start = false;
				return;
			}

			CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
			tFloat positionX = property.positionX;
			if (property.randomPositionX == true)
			{
				positionX = foodData->collisionRadius + (screenSize.width - (foodData->collisionRadius*2.0f)) * CCRANDOM_0_1();
			}

			sCreateEnemyArg arg;
			arg.type = (eEnemyType::TYPE)foodData->type;
			arg.foodID = property.foodID;
			arg.pos = ccp(positionX, screenSize.height);
			arg.speed = m_stageData->scrollSpeed;
			arg.radius = foodData->collisionRadius;
			arg.spriteFilename = foodData->spriteFilename;
			m_logicManager->CreateEnemy(arg);

			m_timeLineIndex++;
			if (m_stageData->timeLine.propertyArray.size() <= (tSize)m_timeLineIndex)
			{
				m_start = false;
				m_stageTimer.Clear();
			
				// notify stage done
				m_stageDelayTimer.Init(m_stageData->lastDelay);
			}
			else
			{
				nStageFormat01::sStage::sTimeLine::sProperty property = m_stageData->timeLine.propertyArray[m_timeLineIndex];
				m_stageTimer.Init(property.time);
			}
		}
	}
}